const express = require("express");
const mongoose = require("mongoose");
const path = require("path");
const fs = require("fs");
const Task = require("../models/Task");
const TaskComment = require("../models/TaskComment");
const TaskReminder = require("../models/TaskReminder");
const TaskProgress = require("../models/TaskProgress");
const TaskAttachment = require("../models/TaskAttachment");
const Group = require("../models/Group");
const GroupMember = require("../models/GroupMember");
const User = require("../models/User");
const auth = require("../middleware/auth");
const NotificationService = require("../services/notificationService");
const {
  uploadSingle,
  uploadMultiple,
  cleanupTempFiles,
} = require("../middleware/upload");

const router = express.Router();

// 权限检查中间件
const checkGroupPermission = async (req, res, next) => {
  try {
    const { groupId } = req.params;
    const membership = await GroupMember.findOne({
      group: groupId,
      user: req.user.id,
      status: "accepted",
    }).lean();

    if (!membership) {
      return res.status(403).json({ message: "非本组成员" });
    }

    req.membership = membership;
    next();
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
};

// 管理员权限检查中间件（用于创建任务）
const checkAdminPermission = async (req, res, next) => {
  try {
    const { groupId } = req.params;
    const membership = await GroupMember.findOne({
      group: groupId,
      user: req.user.id,
      status: "accepted",
      role: { $in: ["owner", "admin"] }, // 只有组长和管理员
    }).lean();

    if (!membership) {
      return res
        .status(403)
        .json({ message: "需要组长或管理员权限才能创建任务" });
    }

    req.membership = membership;
    next();
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
};

// 检查任务权限
const checkTaskPermission = async (req, res, next) => {
  try {
    const { taskId } = req.params;
    const task = await Task.findById(taskId).populate("group").lean();

    if (!task) {
      return res.status(404).json({ message: "任务不存在" });
    }

    const membership = await GroupMember.findOne({
      group: task.group._id,
      user: req.user.id,
      status: "accepted",
    }).lean();

    if (!membership) {
      return res.status(403).json({ message: "无权限访问此任务" });
    }

    req.task = task;
    req.membership = membership;
    next();
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
};

// 创建任务
router.post(
  "/groups/:groupId/tasks",
  auth,
  checkAdminPermission, // 改为管理员权限检查
  async (req, res) => {
    try {
      const { groupId } = req.params;
      const {
        title,
        description = "",
        assignee,
        priority = "medium",
        dueDate,
        tags = [],
        estimatedHours,
        parentTask,
      } = req.body || {};

      if (!title || !String(title).trim()) {
        return res.status(400).json({ message: "任务标题不能为空" });
      }

      // 检查小组是否存在
      const group = await Group.findById(groupId).lean();
      if (!group) {
        return res.status(404).json({ message: "小组不存在" });
      }

      // 检查分配的用户是否为小组成员
      if (assignee) {
        const assigneeMembership = await GroupMember.findOne({
          group: groupId,
          user: assignee,
          status: "accepted",
        }).lean();

        if (!assigneeMembership) {
          return res.status(400).json({ message: "分配的用户不是小组成员" });
        }
      }

      // 检查父任务是否存在且属于同一小组
      if (parentTask) {
        const parent = await Task.findOne({
          _id: parentTask,
          group: groupId,
        }).lean();

        if (!parent) {
          return res
            .status(400)
            .json({ message: "父任务不存在或不属于本小组" });
        }
      }

      const task = await Task.create({
        title: String(title).trim(),
        description: String(description).trim(),
        group: groupId,
        creator: req.user.id,
        assignee: assignee || null,
        priority,
        dueDate: dueDate ? new Date(dueDate) : null,
        tags: Array.isArray(tags)
          ? tags.filter((tag) => String(tag).trim())
          : [],
        estimatedHours: estimatedHours ? Number(estimatedHours) : null,
        parentTask: parentTask || null,
      });

      // 创建任务创建的系统评论
      await TaskComment.create({
        task: task._id,
        author: req.user.id,
        content: `任务已创建`,
        type: "system",
      });

      // 如果有分配人，创建分配通知
      if (assignee) {
        await TaskComment.create({
          task: task._id,
          author: req.user.id,
          content: `任务已分配给 ${assignee}`,
          type: "assignment",
          assignmentChange: {
            from: null,
            to: assignee,
          },
        });

        // 发送任务分配通知
        await NotificationService.createTaskAssignedNotification(
          task._id,
          assignee,
          req.user.id
        );
      }

      const populatedTask = await Task.findById(task._id)
        .populate("creator", "username email")
        .populate("assignee", "username email")
        .populate("group", "name")
        .lean();

      return res.status(201).json(populatedTask);
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取小组任务列表
router.get(
  "/groups/:groupId/tasks",
  auth,
  checkGroupPermission,
  async (req, res) => {
    try {
      const { groupId } = req.params;
      const {
        status,
        assignee,
        priority,
        creator,
        page = 1,
        limit = 20,
        sortBy = "createdAt",
        sortOrder = "desc",
      } = req.query;

      const filter = { group: groupId };

      // 构建查询条件
      if (status) filter.status = status;
      if (assignee) filter.assignee = assignee;
      if (priority) filter.priority = priority;
      if (creator) filter.creator = creator;

      const skip = (Number(page) - 1) * Number(limit);
      const sort = { [sortBy]: sortOrder === "desc" ? -1 : 1 };

      const tasks = await Task.find(filter)
        .populate("creator", "username email")
        .populate("assignee", "username email")
        .populate("group", "name")
        .sort(sort)
        .skip(skip)
        .limit(Number(limit))
        .lean();

      const total = await Task.countDocuments(filter);

      return res.status(200).json({
        tasks,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取单个任务详情
router.get("/tasks/:taskId", auth, checkTaskPermission, async (req, res) => {
  try {
    const { taskId } = req.params;

    const task = await Task.findById(taskId)
      .populate("creator", "username email")
      .populate("assignee", "username email")
      .populate("group", "name")
      .populate("parentTask", "title")
      .populate("dependencies", "title status")
      .lean();

    if (!task) {
      return res.status(404).json({ message: "任务不存在" });
    }

    return res.status(200).json(task);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 更新任务
router.patch("/tasks/:taskId", auth, checkTaskPermission, async (req, res) => {
  try {
    const { taskId } = req.params;
    const {
      title,
      description,
      assignee,
      status,
      priority,
      dueDate,
      tags,
      estimatedHours,
      actualHours,
      progress,
    } = req.body || {};

    const task = await Task.findById(taskId);
    if (!task) {
      return res.status(404).json({ message: "任务不存在" });
    }

    const updates = {};
    const changes = [];

    // 检查权限：只有创建者、分配者或管理员可以修改任务
    const canEdit =
      String(task.creator) === String(req.user.id) ||
      String(task.assignee) === String(req.user.id) ||
      req.membership.role === "owner" ||
      req.membership.role === "admin";

    if (!canEdit) {
      return res.status(403).json({ message: "无权限修改此任务" });
    }

    // 更新字段
    if (title !== undefined) {
      updates.title = String(title).trim();
      changes.push(`标题更新为: ${updates.title}`);
    }
    if (description !== undefined) {
      updates.description = String(description).trim();
    }
    if (priority !== undefined) {
      updates.priority = priority;
      changes.push(`优先级更新为: ${priority}`);
    }
    if (dueDate !== undefined) {
      updates.dueDate = dueDate ? new Date(dueDate) : null;
    }
    if (tags !== undefined) {
      updates.tags = Array.isArray(tags)
        ? tags.filter((tag) => String(tag).trim())
        : [];
    }
    if (estimatedHours !== undefined) {
      updates.estimatedHours = estimatedHours ? Number(estimatedHours) : null;
    }
    if (actualHours !== undefined) {
      updates.actualHours = actualHours ? Number(actualHours) : null;
    }
    if (progress !== undefined) {
      updates.progress = Math.max(0, Math.min(100, Number(progress)));
    }

    // 处理分配变更
    if (assignee !== undefined) {
      if (assignee && assignee !== String(task.assignee)) {
        // 检查新分配的用户是否为小组成员
        const assigneeMembership = await GroupMember.findOne({
          group: task.group,
          user: assignee,
          status: "accepted",
        }).lean();

        if (!assigneeMembership) {
          return res.status(400).json({ message: "分配的用户不是小组成员" });
        }

        updates.assignee = assignee;
        changes.push(`任务重新分配给: ${assignee}`);
      } else if (!assignee && task.assignee) {
        updates.assignee = null;
        changes.push("任务取消分配");
      }
    }

    // 处理状态变更
    if (status !== undefined && status !== task.status) {
      updates.status = status;
      changes.push(`状态从 ${task.status} 变更为 ${status}`);

      if (status === "completed") {
        updates.completedAt = new Date();
        updates.progress = 100;
      } else if (task.status === "completed" && status !== "completed") {
        updates.completedAt = null;
      }
    }

    // 执行更新
    const updatedTask = await Task.findByIdAndUpdate(
      taskId,
      { $set: updates },
      { new: true }
    )
      .populate("creator", "username email")
      .populate("assignee", "username email")
      .populate("group", "name")
      .lean();

    // 创建变更记录
    if (changes.length > 0) {
      await TaskComment.create({
        task: taskId,
        author: req.user.id,
        content: changes.join("; "),
        type: "status_change",
        statusChange:
          status !== undefined ? { from: task.status, to: status } : undefined,
        assignmentChange:
          assignee !== undefined
            ? { from: task.assignee, to: assignee }
            : undefined,
      });

      // 发送任务更新通知
      await NotificationService.createTaskUpdatedNotification(
        taskId,
        req.user.id,
        changes
      );

      // 如果任务完成，发送完成通知
      if (status === "completed") {
        await NotificationService.createTaskCompletedNotification(
          taskId,
          req.user.id
        );
      }

      // 如果重新分配任务，发送分配通知
      if (
        assignee !== undefined &&
        assignee &&
        assignee !== String(task.assignee)
      ) {
        await NotificationService.createTaskAssignedNotification(
          taskId,
          assignee,
          req.user.id
        );
      }
    }

    return res.status(200).json(updatedTask);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 删除任务
router.delete("/tasks/:taskId", auth, checkTaskPermission, async (req, res) => {
  try {
    const { taskId } = req.params;

    const task = await Task.findById(taskId);
    if (!task) {
      return res.status(404).json({ message: "任务不存在" });
    }

    // 只有创建者或组长可以删除任务
    const canDelete =
      String(task.creator) === String(req.user.id) ||
      req.membership.role === "owner";

    if (!canDelete) {
      return res.status(403).json({ message: "无权限删除此任务" });
    }

    // 删除相关评论
    await TaskComment.deleteMany({ task: taskId });

    // 删除任务
    await Task.findByIdAndDelete(taskId);

    return res.status(200).json({ message: "任务已删除" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 获取我的任务
router.get("/my-tasks", auth, async (req, res) => {
  try {
    const {
      status,
      group,
      page = 1,
      limit = 20,
      sortBy = "dueDate",
      sortOrder = "asc",
    } = req.query;

    const filter = {
      $or: [{ assignee: req.user.id }, { creator: req.user.id }],
    };

    if (status) filter.status = status;
    if (group) filter.group = group;

    const skip = (Number(page) - 1) * Number(limit);
    const sort = { [sortBy]: sortOrder === "desc" ? -1 : 1 };

    const tasks = await Task.find(filter)
      .populate("creator", "username email")
      .populate("assignee", "username email")
      .populate("group", "name")
      .sort(sort)
      .skip(skip)
      .limit(Number(limit))
      .lean();

    const total = await Task.countDocuments(filter);

    return res.status(200).json({
      tasks,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        pages: Math.ceil(total / Number(limit)),
      },
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 添加任务评论
router.post(
  "/tasks/:taskId/comments",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { content } = req.body || {};

      if (!content || !String(content).trim()) {
        return res.status(400).json({ message: "评论内容不能为空" });
      }

      const comment = await TaskComment.create({
        task: taskId,
        author: req.user.id,
        content: String(content).trim(),
        type: "comment",
      });

      const populatedComment = await TaskComment.findById(comment._id)
        .populate("author", "username email")
        .lean();

      // 发送评论通知
      await NotificationService.createCommentNotification(taskId, req.user.id);

      return res.status(201).json(populatedComment);
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取任务评论
router.get(
  "/tasks/:taskId/comments",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { page = 1, limit = 20 } = req.query;

      const skip = (Number(page) - 1) * Number(limit);

      const comments = await TaskComment.find({ task: taskId })
        .populate("author", "username email")
        .populate("assignmentChange.from", "username")
        .populate("assignmentChange.to", "username")
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(Number(limit))
        .lean();

      const total = await TaskComment.countDocuments({ task: taskId });

      return res.status(200).json({
        comments,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取任务统计信息
router.get(
  "/groups/:groupId/tasks/stats",
  auth,
  checkGroupPermission,
  async (req, res) => {
    try {
      const { groupId } = req.params;

      const stats = await Task.aggregate([
        { $match: { group: new mongoose.Types.ObjectId(groupId) } },
        {
          $group: {
            _id: "$status",
            count: { $sum: 1 },
          },
        },
      ]);

      const priorityStats = await Task.aggregate([
        { $match: { group: new mongoose.Types.ObjectId(groupId) } },
        {
          $group: {
            _id: "$priority",
            count: { $sum: 1 },
          },
        },
      ]);

      const overdueCount = await Task.countDocuments({
        group: groupId,
        dueDate: { $lt: new Date() },
        status: { $nin: ["completed", "cancelled"] },
      });

      return res.status(200).json({
        statusStats: stats,
        priorityStats: priorityStats,
        overdueCount,
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 任务依赖关系管理

// 添加任务依赖
router.post(
  "/tasks/:taskId/dependencies",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { dependencyTaskId } = req.body || {};

      if (!dependencyTaskId) {
        return res.status(400).json({ message: "缺少依赖任务ID" });
      }

      // 检查依赖任务是否存在且属于同一小组
      const dependencyTask = await Task.findOne({
        _id: dependencyTaskId,
        group: req.task.group._id,
      }).lean();

      if (!dependencyTask) {
        return res
          .status(404)
          .json({ message: "依赖任务不存在或不属于同一小组" });
      }

      // 检查是否已经存在该依赖
      const existingDependency = await Task.findOne({
        _id: taskId,
        dependencies: dependencyTaskId,
      }).lean();

      if (existingDependency) {
        return res.status(409).json({ message: "该依赖关系已存在" });
      }

      // 检查循环依赖
      if (String(taskId) === String(dependencyTaskId)) {
        return res.status(400).json({ message: "任务不能依赖自己" });
      }

      // 检查是否会造成循环依赖
      const wouldCreateCycle = await checkCircularDependency(
        taskId,
        dependencyTaskId
      );
      if (wouldCreateCycle) {
        return res.status(400).json({ message: "添加此依赖会造成循环依赖" });
      }

      // 添加依赖关系
      const updatedTask = await Task.findByIdAndUpdate(
        taskId,
        { $addToSet: { dependencies: dependencyTaskId } },
        { new: true }
      )
        .populate("dependencies", "title status priority")
        .lean();

      // 创建依赖添加的评论
      await TaskComment.create({
        task: taskId,
        author: req.user.id,
        content: `添加了依赖任务: ${dependencyTask.title}`,
        type: "system",
      });

      return res.status(200).json({
        message: "依赖关系添加成功",
        task: {
          _id: updatedTask._id,
          title: updatedTask.title,
          dependencies: updatedTask.dependencies,
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 删除任务依赖
router.delete(
  "/tasks/:taskId/dependencies/:dependencyId",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId, dependencyId } = req.params;

      // 检查依赖是否存在
      const task = await Task.findOne({
        _id: taskId,
        dependencies: dependencyId,
      }).lean();

      if (!task) {
        return res.status(404).json({ message: "依赖关系不存在" });
      }

      // 获取依赖任务信息用于评论
      const dependencyTask = await Task.findById(dependencyId).lean();

      // 删除依赖关系
      const updatedTask = await Task.findByIdAndUpdate(
        taskId,
        { $pull: { dependencies: dependencyId } },
        { new: true }
      )
        .populate("dependencies", "title status priority")
        .lean();

      // 创建依赖删除的评论
      await TaskComment.create({
        task: taskId,
        author: req.user.id,
        content: `移除了依赖任务: ${dependencyTask?.title || dependencyId}`,
        type: "system",
      });

      return res.status(200).json({
        message: "依赖关系删除成功",
        task: {
          _id: updatedTask._id,
          title: updatedTask.title,
          dependencies: updatedTask.dependencies,
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取任务依赖列表
router.get(
  "/tasks/:taskId/dependencies",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;

      const task = await Task.findById(taskId)
        .populate("dependencies", "title status priority dueDate progress")
        .lean();

      if (!task) {
        return res.status(404).json({ message: "任务不存在" });
      }

      return res.status(200).json({
        taskId: task._id,
        taskTitle: task.title,
        dependencies: task.dependencies || [],
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 任务提醒功能

// 设置任务提醒
router.post(
  "/tasks/:taskId/reminders",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const {
        type = "custom",
        title,
        message = "",
        remindAt,
        methods = ["notification"],
        repeat = { enabled: false, interval: "daily", count: 1 },
      } = req.body || {};

      if (!title || !remindAt) {
        return res
          .status(400)
          .json({ message: "缺少必要字段: title, remindAt" });
      }

      // 验证提醒时间不能是过去时间
      if (new Date(remindAt) <= new Date()) {
        return res.status(400).json({ message: "提醒时间不能是过去时间" });
      }

      const reminder = await TaskReminder.create({
        task: taskId,
        user: req.user.id,
        type,
        title: String(title).trim(),
        message: String(message).trim(),
        remindAt: new Date(remindAt),
        methods,
        repeat,
      });

      const populatedReminder = await TaskReminder.findById(reminder._id)
        .populate("task", "title status")
        .populate("user", "username email")
        .lean();

      return res.status(201).json(populatedReminder);
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取我的提醒列表
router.get("/tasks/reminders", auth, async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      type,
      isActive = true,
      sortBy = "remindAt",
      sortOrder = "asc",
    } = req.query;

    const filter = { user: req.user.id };
    if (type) filter.type = type;
    if (isActive !== undefined) filter.isActive = isActive === "true";

    const skip = (Number(page) - 1) * Number(limit);
    const sort = { [sortBy]: sortOrder === "desc" ? -1 : 1 };

    const reminders = await TaskReminder.find(filter)
      .populate("task", "title status priority dueDate")
      .sort(sort)
      .skip(skip)
      .limit(Number(limit))
      .lean();

    const total = await TaskReminder.countDocuments(filter);

    return res.status(200).json({
      reminders,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        pages: Math.ceil(total / Number(limit)),
      },
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 更新提醒
router.patch("/tasks/reminders/:reminderId", auth, async (req, res) => {
  try {
    const { reminderId } = req.params;
    const { title, message, remindAt, isActive, methods, repeat } =
      req.body || {};

    const reminder = await TaskReminder.findOne({
      _id: reminderId,
      user: req.user.id,
    });

    if (!reminder) {
      return res.status(404).json({ message: "提醒不存在" });
    }

    const updates = {};
    if (title !== undefined) updates.title = String(title).trim();
    if (message !== undefined) updates.message = String(message).trim();
    if (remindAt !== undefined) {
      const newRemindAt = new Date(remindAt);
      if (newRemindAt <= new Date()) {
        return res.status(400).json({ message: "提醒时间不能是过去时间" });
      }
      updates.remindAt = newRemindAt;
    }
    if (isActive !== undefined) updates.isActive = Boolean(isActive);
    if (methods !== undefined) updates.methods = methods;
    if (repeat !== undefined) updates.repeat = repeat;

    const updatedReminder = await TaskReminder.findByIdAndUpdate(
      reminderId,
      { $set: updates },
      { new: true }
    )
      .populate("task", "title status")
      .populate("user", "username email")
      .lean();

    return res.status(200).json(updatedReminder);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 删除提醒
router.delete("/tasks/reminders/:reminderId", auth, async (req, res) => {
  try {
    const { reminderId } = req.params;

    const reminder = await TaskReminder.findOneAndDelete({
      _id: reminderId,
      user: req.user.id,
    });

    if (!reminder) {
      return res.status(404).json({ message: "提醒不存在" });
    }

    return res.status(200).json({ message: "提醒已删除" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 获取任务的提醒列表
router.get(
  "/tasks/:taskId/reminders",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { page = 1, limit = 20 } = req.query;

      const skip = (Number(page) - 1) * Number(limit);

      const reminders = await TaskReminder.find({ task: taskId })
        .populate("user", "username email")
        .sort({ remindAt: 1 })
        .skip(skip)
        .limit(Number(limit))
        .lean();

      const total = await TaskReminder.countDocuments({ task: taskId });

      return res.status(200).json({
        taskId,
        reminders,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 辅助函数：检查循环依赖
async function checkCircularDependency(taskId, dependencyId) {
  // 简单的循环依赖检查：如果依赖任务已经依赖当前任务，则形成循环
  const dependencyTask = await Task.findById(dependencyId).lean();
  if (!dependencyTask) return false;

  // 检查依赖任务是否已经依赖当前任务
  if (
    dependencyTask.dependencies &&
    dependencyTask.dependencies.includes(taskId)
  ) {
    return true;
  }

  // 递归检查更深层的循环依赖
  if (dependencyTask.dependencies && dependencyTask.dependencies.length > 0) {
    for (const depId of dependencyTask.dependencies) {
      const hasCycle = await checkCircularDependency(taskId, depId);
      if (hasCycle) return true;
    }
  }

  return false;
}

// 任务进度管理

// 添加任务进度
router.post(
  "/tasks/:taskId/progress",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const {
        progress,
        title,
        description = "",
        workDone = "",
        issues = "",
        nextSteps = "",
        hoursWorked = 0,
        type = "update",
        isMilestone = false,
      } = req.body || {};

      if (!progress || !title) {
        return res
          .status(400)
          .json({ message: "缺少必要字段: progress, title" });
      }

      const progressValue = Number(progress);
      if (progressValue < 0 || progressValue > 100) {
        return res.status(400).json({ message: "进度值必须在0-100之间" });
      }

      // 创建进度记录
      const progressRecord = await TaskProgress.create({
        task: taskId,
        user: req.user.id,
        progress: progressValue,
        title: String(title).trim(),
        description: String(description).trim(),
        workDone: String(workDone).trim(),
        issues: String(issues).trim(),
        nextSteps: String(nextSteps).trim(),
        hoursWorked: Number(hoursWorked) || 0,
        type,
        isMilestone: Boolean(isMilestone),
      });

      // 更新任务进度
      await Task.findByIdAndUpdate(taskId, {
        $set: { progress: progressValue },
      });

      // 如果进度达到100%，更新任务状态为已完成
      if (progressValue === 100) {
        await Task.findByIdAndUpdate(taskId, {
          $set: {
            status: "completed",
            completedAt: new Date(),
          },
        });
      }

      const populatedProgress = await TaskProgress.findById(progressRecord._id)
        .populate("user", "username email")
        .populate("attachments")
        .lean();

      // 创建进度更新的评论
      await TaskComment.create({
        task: taskId,
        author: req.user.id,
        content: `更新进度至 ${progressValue}%: ${title}`,
        type: "status_change",
      });

      // 发送进度更新通知
      await NotificationService.createTaskUpdatedNotification(
        taskId,
        req.user.id,
        [`进度更新至 ${progressValue}%`]
      );

      return res.status(201).json(populatedProgress);
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取任务进度历史
router.get(
  "/tasks/:taskId/progress",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { page = 1, limit = 20, type, isMilestone } = req.query;

      const filter = { task: taskId };
      if (type) filter.type = type;
      if (isMilestone !== undefined)
        filter.isMilestone = isMilestone === "true";

      const skip = (Number(page) - 1) * Number(limit);

      const progressRecords = await TaskProgress.find(filter)
        .populate("user", "username email")
        .populate(
          "attachments",
          "originalName fileName fileSize mimeType category"
        )
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(Number(limit))
        .lean();

      const total = await TaskProgress.countDocuments(filter);

      return res.status(200).json({
        taskId,
        progressRecords,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 更新进度记录
router.patch("/tasks/progress/:progressId", auth, async (req, res) => {
  try {
    const { progressId } = req.params;
    const {
      title,
      description,
      workDone,
      issues,
      nextSteps,
      hoursWorked,
      type,
      isMilestone,
    } = req.body || {};

    const progressRecord = await TaskProgress.findOne({
      _id: progressId,
      user: req.user.id,
    });

    if (!progressRecord) {
      return res.status(404).json({ message: "进度记录不存在" });
    }

    const updates = {};
    if (title !== undefined) updates.title = String(title).trim();
    if (description !== undefined)
      updates.description = String(description).trim();
    if (workDone !== undefined) updates.workDone = String(workDone).trim();
    if (issues !== undefined) updates.issues = String(issues).trim();
    if (nextSteps !== undefined) updates.nextSteps = String(nextSteps).trim();
    if (hoursWorked !== undefined)
      updates.hoursWorked = Number(hoursWorked) || 0;
    if (type !== undefined) updates.type = type;
    if (isMilestone !== undefined) updates.isMilestone = Boolean(isMilestone);

    const updatedProgress = await TaskProgress.findByIdAndUpdate(
      progressId,
      { $set: updates },
      { new: true }
    )
      .populate("user", "username email")
      .populate("attachments")
      .lean();

    return res.status(200).json(updatedProgress);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 删除进度记录
router.delete("/tasks/progress/:progressId", auth, async (req, res) => {
  try {
    const { progressId } = req.params;

    const progressRecord = await TaskProgress.findOne({
      _id: progressId,
      user: req.user.id,
    });

    if (!progressRecord) {
      return res.status(404).json({ message: "进度记录不存在" });
    }

    // 删除关联的附件
    if (progressRecord.attachments && progressRecord.attachments.length > 0) {
      await TaskAttachment.deleteMany({
        _id: { $in: progressRecord.attachments },
      });
    }

    await TaskProgress.findByIdAndDelete(progressId);

    return res.status(200).json({ message: "进度记录已删除" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 附件管理

// 上传附件
router.post(
  "/tasks/:taskId/attachments",
  auth,
  checkTaskPermission,
  uploadMultiple("attachments", 10),
  cleanupTempFiles,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const {
        progressId,
        description = "",
        category = "other",
      } = req.body || {};

      if (!req.files || req.files.length === 0) {
        return res.status(400).json({ message: "没有上传文件" });
      }

      const attachments = [];

      for (const file of req.files) {
        const extension = path.extname(file.originalname);
        const fileCategory = TaskAttachment.getCategoryFromExtension(extension);

        const attachment = await TaskAttachment.create({
          task: taskId,
          progress: progressId || null,
          uploadedBy: req.user.id,
          originalName: file.originalname,
          fileName: file.filename,
          filePath: file.path,
          fileSize: file.size,
          mimeType: file.mimetype,
          extension: extension,
          description: String(description).trim(),
          category: fileCategory,
        });

        attachments.push(attachment);
      }

      const populatedAttachments = await TaskAttachment.find({
        _id: { $in: attachments.map((a) => a._id) },
      })
        .populate("uploadedBy", "username email")
        .lean();

      return res.status(201).json({
        message: `成功上传 ${attachments.length} 个文件`,
        attachments: populatedAttachments,
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 获取任务附件列表
router.get(
  "/tasks/:taskId/attachments",
  auth,
  checkTaskPermission,
  async (req, res) => {
    try {
      const { taskId } = req.params;
      const { page = 1, limit = 20, category, progressId } = req.query;

      const filter = { task: taskId, isDeleted: false };
      if (category) filter.category = category;
      if (progressId) filter.progress = progressId;

      const skip = (Number(page) - 1) * Number(limit);

      const attachments = await TaskAttachment.find(filter)
        .populate("uploadedBy", "username email")
        .populate("progress", "title progress createdAt")
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(Number(limit))
        .lean();

      const total = await TaskAttachment.countDocuments(filter);

      return res.status(200).json({
        taskId,
        attachments,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (err) {
      console.error(err);
      return res.status(500).json({ message: "服务器错误" });
    }
  }
);

// 下载附件
router.get("/attachments/:attachmentId/download", auth, async (req, res) => {
  try {
    const { attachmentId } = req.params;

    const attachment = await TaskAttachment.findOne({
      _id: attachmentId,
      isDeleted: false,
    }).lean();

    if (!attachment) {
      return res.status(404).json({ message: "附件不存在" });
    }

    // 检查用户是否有权限访问该附件（通过任务权限）
    const task = await Task.findById(attachment.task).populate("group").lean();
    if (!task) {
      return res.status(404).json({ message: "关联任务不存在" });
    }

    const membership = await GroupMember.findOne({
      group: task.group._id,
      user: req.user.id,
      status: "accepted",
    }).lean();

    if (!membership) {
      return res.status(403).json({ message: "无权限访问此附件" });
    }

    // 检查文件是否存在
    if (!fs.existsSync(attachment.filePath)) {
      return res.status(404).json({ message: "文件不存在" });
    }

    // 增加下载次数
    await TaskAttachment.findByIdAndUpdate(attachmentId, {
      $inc: { downloadCount: 1 },
    });

    // 设置响应头
    res.setHeader(
      "Content-Disposition",
      `attachment; filename="${encodeURIComponent(attachment.originalName)}"`
    );
    res.setHeader("Content-Type", attachment.mimeType);
    res.setHeader("Content-Length", attachment.fileSize);

    // 发送文件
    res.sendFile(path.resolve(attachment.filePath));
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 更新附件信息
router.patch("/attachments/:attachmentId", auth, async (req, res) => {
  try {
    const { attachmentId } = req.params;
    const { description, category } = req.body || {};

    const attachment = await TaskAttachment.findOne({
      _id: attachmentId,
      uploadedBy: req.user.id,
      isDeleted: false,
    });

    if (!attachment) {
      return res.status(404).json({ message: "附件不存在" });
    }

    const updates = {};
    if (description !== undefined)
      updates.description = String(description).trim();
    if (category !== undefined) updates.category = category;

    const updatedAttachment = await TaskAttachment.findByIdAndUpdate(
      attachmentId,
      { $set: updates },
      { new: true }
    )
      .populate("uploadedBy", "username email")
      .lean();

    return res.status(200).json(updatedAttachment);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 删除附件
router.delete("/attachments/:attachmentId", auth, async (req, res) => {
  try {
    const { attachmentId } = req.params;

    const attachment = await TaskAttachment.findOne({
      _id: attachmentId,
      uploadedBy: req.user.id,
      isDeleted: false,
    });

    if (!attachment) {
      return res.status(404).json({ message: "附件不存在" });
    }

    // 标记为已删除（软删除）
    await TaskAttachment.findByIdAndUpdate(attachmentId, {
      $set: { isDeleted: true },
    });

    // 可选：物理删除文件
    if (fs.existsSync(attachment.filePath)) {
      fs.unlinkSync(attachment.filePath);
    }

    return res.status(200).json({ message: "附件已删除" });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

// 获取我的附件列表
router.get("/attachments/my", auth, async (req, res) => {
  try {
    const { page = 1, limit = 20, category, taskId } = req.query;

    const filter = { uploadedBy: req.user.id, isDeleted: false };
    if (category) filter.category = category;
    if (taskId) filter.task = taskId;

    const skip = (Number(page) - 1) * Number(limit);

    const attachments = await TaskAttachment.find(filter)
      .populate("task", "title status")
      .populate("progress", "title progress")
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(Number(limit))
      .lean();

    const total = await TaskAttachment.countDocuments(filter);

    return res.status(200).json({
      attachments,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        pages: Math.ceil(total / Number(limit)),
      },
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

module.exports = router;
